<template>
  <div clsss="edit-info">
    <el-dialog
      v-model="dialogVisible"
      :title="titleInfo"
      width="50%"
      :close-on-click-modal="false"
      @close="handleClose"
    >
      <el-form
        ref="listQueryRef"
        :rules="listQueryRules"
        :model="listQuery"
        label-width="120"
      >
        <el-form-item label="搜索关键字" prop="keyword">
          <el-input
            class="!w-[300px]"
            v-model="listQuery.keyword"
            placeholder="请输入企业名称或统一社会信用代码 "
            autocomplete="off"
            clearable
          />
          <div class="ml10">
            <el-button
              type="primary"
              :disabled="!listQuery.keyword"
              @click="handleInsert"
              >一键录入公司信息</el-button
            >
          </div>
        </el-form-item>
        <div v-if="flagData">
          <el-form-item
            label="公司名称
          "
            prop="name"
          >
            <el-input
              class="!w-[300px]"
              :disabled="flagData"
              v-model="listQuery.name"
              placeholder="请输入公司名称 "
              autocomplete="off"
              clearable
            />
          </el-form-item>
          <el-form-item label="社会信用代码" prop="tax_code">
            <el-input
              class="!w-[300px]"
              :disabled="flagData"
              v-model="listQuery.tax_code"
              autocomplete="off"
              maxlength="18"
              placeholder="请输入社会信用代码"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="法人代表
                "
            prop="legal"
          >
            <el-select
              clearable
              class="select-box"
              filterable
              :disabled="flagData"
              :filter-method="selectFilter"
              v-model="listQuery.legal"
              placeholder="请选择法人代表"
            >
              <el-option
                v-for="item in legalList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="注册资金(万元)
                  "
            prop="register_fund"
          >
            <el-input
              class="!w-[300px]"
              @input="
                listQuery.register_fund = listQuery.register_fund.replace(
                  /^\D*(\d*(?:\.\d{0,2})?).*$/g,
                  '$1'
                )
              "
              :disabled="flagData"
              v-model="listQuery.register_fund"
              placeholder="请输入注册资金(万元)
                  "
              autocomplete="off"
              clearable
            />
          </el-form-item>
          <el-form-item label="税务等级" prop="tax_level">
            <el-select
              clearable
              class="select-box"
              v-model="listQuery.tax_level"
              placeholder="请选择税务等级"
            >
              <el-option
                v-for="item in taxLevelList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="经营范围
                  "
            prop="business"
          >
            <el-input
              class="!w-[300px]"
              :disabled="flagData"
              v-model="listQuery.business"
              placeholder="请输入经营范围
                  "
              autocomplete="off"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="企业注册地址

                  "
            prop="address"
          >
            <el-input
              class="!w-[300px]"
              :disabled="flagData"
              v-model="listQuery.address"
              placeholder="请输入企业注册地址

                  "
              autocomplete="off"
              clearable
            />
          </el-form-item>
          <el-form-item label="企业成立时间" prop="establish_time">
            <el-date-picker
              style="width: 300px"
              v-model="listQuery.establish_time"
              type="date"
              :disabled="flagData"
              value-format="YYYY-MM-DD"
              placeholder="请选择企业成立时间"
            />
          </el-form-item>
          <el-form-item label="高管" prop="officer">
            <el-select
              class="select-box"
              clearable
              v-model="listQuery.officer"
              multiple
              @change="selectChange"
              placeholder="请选择高管"
            >
              <el-option
                v-for="item in legalList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </div>
        <!-- <el-form-item label="股东" prop="officer">
          <el-select
            class="select-box"
            clearable
            v-model="listQuery.shareholder"
            multiple
            @change="selectChange"
            placeholder="请选择"
          >
            <el-option
              v-for="item in legalList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer" v-if="flagData">
          <el-button @click="handleClose" type="danger">取消</el-button>
          <el-button type="primary" @click="handleSubmit"> 提交 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { message } from "@/utils/message";
import { getSessionKey } from "@/utils/auth";
import {
  peopleInsert,
  companyUpdate,
  companyInsert
} from "@/api/personnelPage";
import { peopleSelect, gongsi } from "@/api/companyList";
import {
  reactive,
  ref,
  inject,
  onMounted,
  defineProps,
  defineEmits,
  nextTick,
  defineExpose,
  watch
} from "vue";
import { any } from "vue-types";
const listQueryRef = ref("");
const dataObj = ref({});
const titleText = ref("");
const flagData = ref(false);
const listQuery = ref({
  name: "",
  tax_code: "",
  // legal: "",
  register_fund: "",
  tax_level: "",
  business: "",
  address: "",
  establish_time: "",
  officer: any,
  // shareholder: "",
  // keyword: "",
  admin_id: getSessionKey().admin_id
});
const taxLevelList = ref([
  {
    name: "小规模",
    id: 1
  },
  {
    name: "一般纳税人",
    id: 2
  }
]);
const validateCreditCode = (rule, value, callback) => {
  const reg = /^[0-9ABCDEFGHJKLMNPQRSTWXYZ]{18}$/;
  if (!value) {
    return callback(new Error("社会信用代码不能为空"));
  } else if (!reg.test(value)) {
    return callback(new Error("社会信用代码格式不正确"));
  } else {
    callback();
  }
};
onMounted(() => {
  getList();
});
const handleInsert = () => {
  const params = {
    keyword: listQuery.value.keyword
  };
  gongsi(params).then(res => {
    console.log(res, "====----");
    if (res.code == 200) {
      const data = res.data;
      flagData.value = true;
      listQuery.value = {
        tax_level: 1,
        ...data
      };
    }
    console.log(listQuery.value);
  });
};
const selectFilter = val => {
  console.log("筛选", val);
  if (!val) {
    return;
  }
  const params = {
    name: val,
    admin_id: getSessionKey().admin_id
  };
  peopleSelect(params).then(res => {});
};
const dialogVisible = ref(false);
const listQueryId = ref("");
const opneDialogVisible = data => {
  if (props.isEdit == "1") {
    flagData.value = true;
    const rowData = JSON.parse(JSON.stringify(data));
    console.log(rowData, "=---参数");
    const numberArray = rowData.officer ? rowData.officer.split(",") : [];
    const shareholderArray = rowData?.shareholder.split(",");
    rowData.officer = numberArray.map(Number);
    rowData.shareholder = shareholderArray.map(Number);
    listQuery.value.id = rowData.id;
    listQueryId.value = rowData.id;
    listQuery.value.name = rowData.name;
    listQuery.value.tax_code = rowData.tax_code;
    listQuery.value.legal = rowData.legal;
    listQuery.value.register_fund = rowData.register_fund;
    listQuery.value.tax_level = rowData.tax_level;
    listQuery.value.business = rowData.business;
    listQuery.value.address = rowData.address;
    listQuery.value.establish_time = rowData.establish_time;
    listQuery.value.officer = rowData.officer;
    // listQuery.value.shareholder = rowData.shareholder;
  } else {
    listQuery.value.name = "";
    listQuery.value.name = "";
    listQuery.value.tax_code = "";
    listQuery.value.legal = "";
    listQuery.value.tax_level = 1;
    listQuery.value.register_fund = "";
    listQuery.value.business = "";
    listQuery.value.address = "";
    listQuery.value.establish_time = "";
    listQuery.value.officer = "";
    listQuery.value.shareholder = "";
    console.log(listQuery.value);
  }
  dialogVisible.value = true;
};

const getList = async () => {
  const obj = {
    name: "",
    admin_id: getSessionKey().admin_id
  };
  const res = await peopleSelect(obj);
  if (res.code == 200) {
    const dataList = res.data;
    legalList.value = dataList;
  }
};
const legalList = ref([]);
const listQueryRules = {
  name: [{ required: true, message: "请输入公司名称", trigger: "blur" }],
  tax_code: [
    { required: true, message: "请输入社会信用代码", trigger: "blur" },
    { validator: validateCreditCode, trigger: "change" }
  ],
  legal: [{ required: true, message: "请输入法人代表", trigger: "blur" }]
};
const props = defineProps({
  titleInfo: {
    type: String,
    default: ""
  },
  isEdit: {
    type: String,
    default: ""
  }
});
const handleClose = () => {
  flagData.value = false;
  listQueryRef.value.resetFields(); // 清除表单校验以及表单数据初始化
  dialogVisible.value = false;
};
const disabledDate = time => {
  return time.getTime() > Date.now();
};
const emit = defineEmits(["handleSubmit"]);
const handleSubmit = () => {
  listQueryRef.value.validate(async valid => {
    if (valid) {
      // 添加
      const parmasData = listQuery;
      parmasData.value.officer = parmasData.value.officer
        ? parmasData.value.officer.join(",")
        : "";
      parmasData.value.admin_id = getSessionKey().admin_id;
      console.log(parmasData.value);

      const params = {
        admin_id: getSessionKey().admin_id,
        name: parmasData.value.legal,
        status: 1
      };
      const res = await peopleInsert(params);
      const dataID = res.data;
      parmasData.value.legal = dataID;
      // emit("handleSubmit", parmasData);
      // handleClose();
      console.log(parmasData.value, "legallegallegal");
      if (props.titleInfo == "添加公司") {
        companyInsert(parmasData.value).then(res => {
          console.log(res, "resres");
          message(res.msg, { type: "success" });
          emit("handleSubmit", listQuery);
          handleClose();
        });
        // parmas.admin_id = getSessionKey().admin_id;
      } else {
        // 公司修改
        parmasData.value.id = listQueryId.value;
        delete parmasData.value.legal;
        companyUpdate(parmasData.value).then(res => {
          console.log(res, "resres");
          message(res.msg, { type: "success" });

          emit("handleSubmit", listQuery);
          handleClose();
        });
      }
    }
  });
};
defineExpose({ opneDialogVisible }); //子组件需要把数据导出去
</script>

<style lang="scss" scoped>
.select-box {
  width: 300px;
}

.ml10 {
  margin-left: 10px;
}
</style>
